package net.xdclass.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.interceptor.LoginInterceptor;
import net.xdclass.model.LoginUser;
import net.xdclass.model.UserDO;
import net.xdclass.mapper.UserMapper;
import net.xdclass.request.UserLoginRequest;
import net.xdclass.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.xdclass.util.JWTUtil;
import net.xdclass.util.JsonData;
import net.xdclass.vo.UserVo;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 二当家小D
 * @since 2023-04-26
 */
@Service
public class UserServiceImpl implements UserService {


    @Resource
    private UserMapper userMapper;

    @Override
    public JsonData login(UserLoginRequest userLoginRequest) {
        //检测用户是否注册
        List<UserDO> userDOS = userMapper.selectList(new QueryWrapper<UserDO>().eq("mail", userLoginRequest.getMail()));
        //不存在直接返回
        if (CollectionUtils.isEmpty(userDOS) && userDOS.size() <= 0) {
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNREGISTER);
        }
        //把密码进行加密然后与代码数据库匹配
        UserDO userDO = userDOS.get(0);
        String md5Crypt = Md5Crypt.md5Crypt(userLoginRequest.getPwd().getBytes(), userDO.getSecret());
        if (!StringUtils.equals(userDO.getPwd(), md5Crypt)) {
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);
        }
        //生成token
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(userDO,loginUser);
        String token = JWTUtil.generateToken(loginUser);
        return JsonData.buildSuccess(token);
    }

    @Override
    public UserVo findUserDetail() {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        UserDO userDO = userMapper.selectOne(new QueryWrapper<UserDO>().eq("id", loginUser.getId()));
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(userDO,userVo);
        return userVo;
    }
}
